package com.lry.basic.juc;

public class TestHolderCount {
	
	static final class HoldCounter {
        int count = 0;
        final long tid = Thread.currentThread().getId();
		@Override
		public String toString() {
			return "HoldCounter [count=" + count + ", tid=" + tid + "]";
		}
        
     }
	 static final class ThreadLocalHoldCounter extends ThreadLocal<HoldCounter> {
        public HoldCounter initialValue() {
           return new HoldCounter();
        }
	 }
	 //这上面的代码全是读写锁的源码
	 final static ThreadLocalHoldCounter readHolds = new ThreadLocalHoldCounter();
	 //看这种方式去保存每个线程的获锁次数
	 public static void lockShared(){
		 if(readHolds.get().tid==Thread.currentThread().getId()){
			 readHolds.get().count++;
		 }
	 }
	 public static void main(String[] args) {
		 lockShared();
		 lockShared();
		 new Thread(new Runnable() {
			@Override
			public void run() {
				lockShared();
				lockShared();
				lockShared();
				System.out.println(readHolds.get());
			}
		}).start();
		 new Thread(new Runnable() {
				@Override
				public void run() {
					lockShared();
					System.out.println(readHolds.get());
				}
			}).start();
		 System.out.println(readHolds.get());
	 }
}